<script>
import { mapState, mapActions, mapMutations } from "vuex";
import $api from "@/API/index.js"; 
import $store from "@/store/index.js";
import AppSocket from "@/utils/webSocket.js";
import storage from "@/utils/storage.js";
import { endLiveRoom, emitRoom } from "@/API/newLive.js";

import { getInit } from "@/API/API/common.js";
import stoarge from "@/utils/utils/stoarge.js";

export default {
    data() {
        return {
            timer: null,
            permissionListener: null,
        };
    },
    async mounted() {
        // #ifdef H5
        if (typeof window.entryUrl === "undefined" || window.entryUrl === "") {
            window.entryUrl = window.location.href.split("#")[0];
        }
        if (window.location.href.indexOf("?#") < 0) {
            window.location.href = window.location.href.replace("#", "?#");
        }
        // #endif
    },
    async onLaunch() {
        console.log("App Launch");
        getInit().then((res) => {
            stoarge.setInitData(res.data);
        });
        uni.setStorageSync("isFirstLogin", true);

        if (!uni.getStorageSync("isOpen")) {
            uni.setStorageSync("isOpen", false);
        }
        let configInfo = uni.getStorageSync("configInfo") || "";
        if (configInfo) {
            $store.commit("updateConfigItem", {
                key: "configInfo",
                val: configInfo,
            });
        }
        let isGzhLogin = uni.getStorageSync("isGzhLogin") || false;
        $store.commit("updateUserItem", {
            key: "isGzhLogin",
            val: isGzhLogin,
        });
        let arr = [
            "autograph",
            "userInfo",
            "location",
            "appLogin",
            "loginType",
        ];
        arr.map((key) => {
            let val = uni.getStorageSync(key) || "";
            // #ifdef H5
            val = isGzhLogin ? val : "";
            // #endif
            $store.commit("updateUserItem", {
                key,
                val,
            });
            // #ifdef APP-PLUS
            if (key == "userInfo") {
                $store.commit("updateUserItem", {
                    key: "isShowLogin",
                    val: val && val.id ? false : true,
                });
            }
            // #endif
        });
        let { commonOptions } = this;
        let { coach_id = 0 } = commonOptions;
        if (coach_id) {
            commonOptions.coach_id = 0;
            $store.commit("updateUserItem", {
                key: "commonOptions",
                val: commonOptions,
            });
        }
        this.initIndex();

        if (storage.getLiveRoomInfo() && storage.getLiveRoomInfo().id) {
            if (storage.getLiveRoomInfo().user_id == storage.getUserID()) {
                console.log("关闭直播");
                //还没有退出直播 关播
                endLiveRoom(storage.getLiveRoomInfo().id);
                storage.emitRoomAllClear();
            } else {
                console.log("退出直播间");
                emitRoom(this.live_id);
                storage.emitRoomAllClear();
            }
        }

        AppSocket.initSocket();

        console.log("AAAAAAAA", uni.getStorageSync("userInfo"));
    },
    async onShow() {
        var that = this;
        setInterval(function () {
            that.updateUserLocation();
        }, 10000);
        if (this.timer) {
            clearInterval(this.timer);
        }
        let { coach_position = 0 } = this.userInfo;
        let { id: coachId = 0, status = 0 } = this.coachInfo;
        if (coach_position == 1) {
            if (!coachId) {
                await this.getCoachInfo();
            }
            $store.commit("updateUserItem", {
                key: "locationChange",
                val: true,
            });
        }
        uni.onNetworkStatusChange((res) => {
            let { isConnected } = res;
            if (isConnected) return;
            let methodArr = ["updateServiceItem", "updateTechnicianItem"];
            methodArr.map((item) => {
                $store.commit(item, {
                    key: "pageActive",
                    val: false,
                });
            });
        });
    },
    async onHide() {
        let { coach_position = 0 } = this.userInfo;
        let { status = 0 } = this.coachInfo;
        if (!coach_position || status != 2) return;
        $store.commit("updateUserItem", {
            key: "locationChange",
            val: false,
        });
        // #ifdef H5
        if (this.$jweixin.isWechat()) {
            await this.$jweixin.wxReady2();
            this.toHidePage();
            this.timer = setInterval(() => {
                this.toHidePage();
            }, 60000);
        }
        // #endif
    },
    onUnload() {
        uni.offLocationChange((res) => {
            console.log("====offLocationChange onUnload", res);
        });
    },

    watch: {
        locationChange(newVal, oldVal) {
            if (newVal) {
                uni.startLocationUpdate({
                    complete: (msg) =>
                        console.log(`startLocationUpdate API complete`, msg),
                });
            } else {
                uni.stopLocationUpdate({
                    complete: (msg) =>
                        console.log(`stopLocationUpdate API complete`, msg),
                });
            }
        },
        "configInfo.attendant_name"(newVal, oldVal) {
            if (newVal) {
                this.mergeLocaleMessage();
            }
        },
    },
    computed: mapState({
        configInfo: (state) => state.config.configInfo,
        old_attendant_name: (state) => state.config.old_attendant_name,
        commonOptions: (state) => state.user.commonOptions,
        locationChange: (state) => state.user.locationChange,
        locationChangeUnix: (state) => state.user.locationChangeUnix,
        userInfo: (state) => state.user.userInfo,
        coachInfo: (state) => state.user.coachInfo,
    }),
    methods: {
        ...mapActions(["getConfigInfo", "getUserInfo", "getCoachInfo"]),
        // 定时修改用户经纬度
        async updateUserLocation() {
            let that = this;
            // uni.getLocation({
            // 	type:'gcj02',
            // 	success: function(res) {
            // 			 that.$api.user.edit_lat_lng({
            // 				lat:res.latitude,
            // 				lng:res.longitude
            // 			})

            // 	},
            // })
        },
        async initIndex() {
            let that = this;
            let { coach_position = 0 } = that.userInfo;
            uni.onLocationChange((res) => {
                let { latitude: lat, longitude: lng } = res;
                that.toChangeLocation({
                    lat,
                    lng,
                });
            });
            if (coach_position == 1) {
                let { id: coachId = 0 } = that.coachInfo;
                if (!coachId) {
                    await that.getCoachInfo();
                }
                $store.commit("updateUserItem", {
                    key: "locationChange",
                    val: true,
                });
            }
            let {
                primaryColor = "#606DCE",
                plugAuth = {},
                tabBar = [],
            } = that.configInfo;
            let mineInd = tabBar.findIndex((item) => {
                return item.id == 5;
            });
            // if ((primaryColor && plugAuth.length > 0) || mineInd != -1) return
            await that.getConfigInfo();
        },
        async mergeLocaleMessage() {
            let zh = JSON.parse(JSON.stringify(this.$i18n.messages.zh));
            let { attendant_name: name } = this.configInfo;
            let oldName = this.old_attendant_name;
            let reg = new RegExp(oldName, "g");
            for (let i in zh.action) {
                if (zh.action[i].includes(oldName)) {
                    zh.action[i] = zh.action[i].replace(reg, name);
                }
            }
            this.$i18n.mergeLocaleMessage("zh", zh);
            $store.commit("updateConfigItem", {
                key: "old_attendant_name",
                val: name,
            });
        },
        async toHidePage() {
            let { latitude: lat, longitude: lng } =
                await this.$jweixin.getWxLocation();
            if (lat && lng) {
                let val = this.$util.DateToUnix(
                    this.$util.formatTime(new Date(), "YY-M-D h:m:s")
                );
                $store.commit("updateUserItem", {
                    key: "locationChangeUnix",
                    val,
                });
                this.toChangeLocation({
                    lat,
                    lng,
                });
            }
        },
        async toChangeLocation(param) {
            let { lat, lng } = param;
            let { id = 0, coach_position = 0 } = this.userInfo;
            let { lat: coach_lat, lng: coach_lng, status = 0 } = this.coachInfo;
            let { locationChangeUnix } = this;
            let curUnix = this.$util.DateToUnix(
                this.$util.formatTime(new Date(), "YY-M-D h:m:s")
            );
            let second = 3;
            // #ifdef APP-PLUS
            second = 1;
            // #endif
            let isMin =
                curUnix - locationChangeUnix <= second ||
                curUnix - locationChangeUnix >= 60;
            let isSame = coach_lat * 1 == lat && coach_lng * 1 == lng;
            if (!coach_position || status != 2 || !isMin || isSame) return;

            let val = this.$util.DateToUnix(
                this.$util.formatTime(new Date(), "YY-M-D h:m:s")
            );
            $store.commit("updateUserItem", {
                key: "locationChangeUnix",
                val,
            });

            let key = `${lat},${lng}`;
            try {
                let data = await this.$api.base.getMapInfo({
                    location: key,
                });
                let { status, result } = JSON.parse(data);
                if (status == 0) {
                    let { address } = result;
                    await this.$api.technician.coachUpdate({
                        lat,
                        lng,
                        address,
                    });
                    await this.getCoachInfo();
                }
            } catch (e) {
                uni.stopLocationUpdate({
                    complete: (msg) =>
                        console.log(`stopLocationUpdate API complete`, msg),
                });
            }
        },
    },
};
</script>

<style lang="scss">
@import "uview-ui/index.scss";
@import "/styles/index.wxss";

/* #ifdef H5 */
uni-page-head {
    display: none;
}

/* #endif */

page {
    font-size: 28rpx;
    color: #222;
    line-height: 1.5;
    background: #f6f6f6;
    font-family: -apple-system-font, Helvetica Neue, Helvetica, sans-serif;
}

input {
    // font-family: PingFangSC-Medium, PingFang SC, -apple-system-font, Helvetica Neue, Helvetica, sans-serif;
}

// input::-webkit-input-placeholder {
// 	/* WebKit browsers */
// 	color: #A9A9A9;
// }

// input:-moz-placeholder {
// 	/* Mozilla Firefox 4 to 18 */
// 	color: #A9A9A9;
// }

// input::-moz-placeholder {
// 	/* Mozilla Firefox 19+ */
// 	color: #A9A9A9;
// }

// input:-ms-input-placeholder {
// 	/* Internet Explorer 10+ */
// 	color: #A9A9A9;
// }

view {
    box-sizing: border-box;
}

image {
    display: block;
}

.h5-image {
    background-position: center center;
    background-size: cover;
    background-repeat: no-repeat;
}

/*隐藏滚动条*/
// ::-webkit-scrollbar {
// 	width: 0;
// 	height: 0;
// 	color: transparent;
// }

/* #ifdef MP-BAIDU */
.swan-button.swan-button-radius-ios {
    border-radius: 0;
}

/* #endif */

/*每个页面公共css */
/*#ifndef APP-PLUS-NVUE*/

.demo-tag {
    display: flex;
    flex-wrap: wrap;
    margin-top: 5px;
    margin-left: -8rpx;
}

view,
text {
    line-height: 1;
}

.demo-tag-text {
    margin-bottom: 10rpx;
    margin-left: 8px;
    margin-right: 0rpx !important;
}

::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
    color: transparent;
}

/*#endif*/

.nvue-flex {
    display: flex;
    flex-direction: column;
    align-items: center;
    overflow: hidden;
}

::-webkit-scrollbar {
    display: none;
    width: 0 !important;
    height: 0 !important;
    -webkit-appearance: none;
    background: transparent;
    color: transparent;
}

.flex-1 {
    flex: 1;
}

.flex {
    display: flex;
}

.row {
    flex-direction: row;
}

.column {
    flex-direction: column;
}

.align-center {
    align-items: center;
}

.align-base {
    align-items: baseline;
}

.align-end {
    align-items: flex-end;
}

.align-start {
    align-items: flex-start;
}

.just-between {
    justify-content: space-between;
}

.just-around {
    justify-content: space-around;
}

.just-end {
    justify-content: flex-end;
}

.just-center {
    justify-content: center;
}

.just-start {
    justify-content: flex-start;
}

.f-14 {
    font-size: 14rpx;
}

.f-20 {
    font-size: 20rpx;
}
.fb-20 {
    font-size: 20rpx;
    font-weight: bold;
}

.f-22 {
    font-size: 22rpx;
}

.fb-22 {
    font-size: 22rpx;
    font-weight: bold;
}

.f-24 {
    font-size: 24rpx;
}

.fb-24 {
    font-size: 24rpx;
    font-weight: bold;
}

.f-26 {
    font-size: 26rpx;
}
.fb-26 {
    font-size: 26rpx;
    font-weight: bold;
}
.f-28 {
    font-size: 28rpx;
}
.fb-28 {
    font-size: 28rpx;
    font-weight: bold;
}

.f-30 {
    font-size: 30rpx;
}

.fb-30 {
    font-size: 30rpx;
    font-weight: bold;
}

.f-32 {
    font-size: 32rpx;
}

.fb-32 {
    font-size: 32rpx;
    font-weight: bold;
}

.f-34 {
    font-size: 34rpx;
}

.fb-34 {
    font-size: 34rpx;
    font-weight: bold;
}

.f-36 {
    font-size: 36rpx;
}

.fb-36 {
    font-size: 36rpx;
    font-weight: bold;
}

.f-40 {
    font-size: 40rpx;
}
.fb-40 {
    font-size: 40rpx;
    font-weight: bold;
}
.f-44 {
    font-size: 44rpx;
}
.fb-44 {
    font-size: 44rpx;
    font-weight: bold;
}
.f-48 {
    font-size: 48rpx;
}
.f-52 {
    font-size: 52rpx;
}
.fb-52 {
    font-size: 52rpx;
    font-weight: bold;
}
.f-56 {
    font-size: 56rpx;
}
.fb-56 {
    font-size: 56rpx;
    font-weight: bold;
}

.t-c {
    text-align: center;
}

.t-r {
    text-align: right;
}

.t-l {
    text-align: left;
}

// 自定义tabBar可以使用的
.paddingBottom {
    padding-bottom: Max(
        calc(20rpx + var(--bottom-height)),
        calc(env(safe-area-inset-bottom) + var(--bottom-height))
    ) !important;
}

.safe-area {
    padding-bottom: Max(env(safe-area-inset-bottom), 20rpx) !important;
}

.limit-num-line {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: var(--limit-num);
    overflow: hidden;
    text-overflow: ellipsis;
}

swiper,
swiper-item {
    width: 100%;
    height: 100%;
}

view,
text {
    line-height: 1;
}

.bg-img-set {
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
}

.arrow {
    width: 12rpx;
    height: 20rpx;
}

.active {
    color: $theme-color !important;
}
.wrap {
    width: 100%;
    overflow: hidden;

    .wrap-bg {
        position: absolute;
        left: 0;
        top: calc(0px - var(--navigation-height));
        width: 100%;
        z-index: -1;
    }
}
</style>